package com.biwin.module.org.starter.service.impl;

import com.biwin.common.app.exception.BwNotFoundException;
import com.biwin.module.org.api.dto.PositionDto;
import com.biwin.module.org.api.enums.BwPositionExceptionEnum;
import com.biwin.module.org.api.service.IPositionService;
import com.biwin.module.org.api.vo.PositionVo;
import com.biwin.module.org.domain.entity.Position;
import com.biwin.module.org.domain.mapper.PositionMapper;
import com.biwin.module.org.starter.repository.IPositionRepository;
import com.biwin.module.orm.starter.service.AbstractCurdService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

/**
 * Position Service Implementation
 *
 * @author biwin
 * @since 0.0.1
 */
@Service
public class PositionServiceImpl extends AbstractCurdService<Position, PositionVo, Long> implements IPositionService<Position, PositionVo, Long> {
    private final IPositionRepository positionRepository;

    private final PositionMapper positionMapper;

    public PositionServiceImpl(IPositionRepository positionRepository, PositionMapper positionMapper) {
        super(positionRepository);
        this.positionRepository = positionRepository;
        this.positionMapper = positionMapper;
    }

    @Override
    protected PositionVo toVo(Position entity) {
        return positionMapper.toVo(entity);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public PositionVo add(PositionDto positionDto) {
        Position position = positionMapper.toEntity(positionDto);
        positionRepository.save(position);
        return toVo(position);
    }

    @Override
    public PositionVo findByName(String positionName) {
        Assert.notNull(positionName, "positionName must be not null");
        Position position =
                positionRepository.findByName(positionName).orElseThrow(() -> new BwNotFoundException(BwPositionExceptionEnum.POSITION_NOT_EXIST));
        return toVo(position);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public PositionVo update(PositionDto positionDto) {
        Position position = positionMapper.mergeEntity(positionDto, findByIdE(positionDto.getId()));
        positionRepository.save(position);
        return toVo(position);
    }

    @Override
    public boolean disable(Long id) {
        return enablePosition(id, false);
    }

    @Override
    public boolean enable(Long id) {
        return enablePosition(id, true);
    }

    private boolean enablePosition(Long id, boolean enabled) {
        Position position = super.findByIdE(id);
        position.setEnabled(enabled);
        positionRepository.save(position);
        return true;
    }
}
